<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
<%@ page import="com.vb.webpress.data.*"%>
<%@ page import="javax.servlet.http.HttpSession"%>
<% 
	String[] type = NewsDAO.findType();
	int typeLength = type.length;
	
	boolean login = false;
	session = request.getSession(false);

	if(session != null){
		
		if(session.getAttribute("account") != null)
			login = true;
		else
			session.invalidate();
		
		if(request.getParameter("action") != null
				&& request.getParameter("action").equals("logout")){
			session.invalidate();
			login = false;
		}
	}

	if(request.getParameter("action") != null
			&& request.getParameter("action").equals("login")){
		if(AccountDAO.validateAccount(request.getParameter("account")
				, request.getParameter("password"))){
			login = true;
			
			session = request.getSession(true);
			Cookie cookie = new Cookie("JSESSIONID", session.getId());
			cookie.setMaxAge(Integer.MAX_VALUE);
			response.addCookie(cookie);

			if(request.getParameter("timeout") != null)
				session.setMaxInactiveInterval(Integer.MAX_VALUE);
			else
				session.setMaxInactiveInterval(3 * 60 * 60);	
				
			session.setAttribute("account", request.getParameter("account"));
			
		}else{
			response.sendRedirect("/WebPress/login.jsp?status=wrong");//登录失败，跳转到登录页面，带入错误信息
		}
	}
	
%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<%@page import="javax.servlet.http.HttpSession"%>
<%@page import="java.util.Enumeration"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Index</title>
</head>
<body>
<%if(login){ %>
<p><%="Welcome " + session.getAttribute("account")%></p>
<a href="/WebPress/index.jsp?action=logout">Logout</a>
<a href="/WebPress/release.jsp">Release</a>
<%}else{ %>
<form action="/WebPress/index.jsp?action=login" method="post">
<table>
	<tr>
		<td>ID</td>
		<td><input type="text" name="account"></td>
	</tr>
	<tr>
		<td>PWD</td>
		<td><input type="password" name="password"></td>
	</tr>
	<tr>
		<td>Login Automatically</td>
		<td><input type="radio" name="timeout"
			value="<%=Integer.MAX_VALUE%>"></td>
	</tr>
	<tr>
		<td></td>
		<td><input type="submit" value="Login"></td>
	</tr>
</table>

</form>
<%}%>
<% 
	for(int i = 0; i < typeLength; i++){
%>
<div>
<h2><%=type[i]%></h2>
<%News[] newsArray = NewsDAO.findNewsByType(type[i], 0, 4);%>
<table>

	<% for(int j = 0; j < newsArray.length; j++){
					if(newsArray[j] != null){
				%>
	<tr>
		<td><a
			href=<%="/WebPress/news.jsp?newsid=" + newsArray[j].getId()%>><%=newsArray[j].getTitle()%></a>
		</td>
		<td><%=newsArray[j].getTime().toString().substring(0, 19)%></td>
	</tr>
	<% 	
					}
				}
				%>
	<tr>
		<td><a href=<%="/WebPress/sortednews.jsp?type=" + type[i]%>>&lt&ltmore</a>
		</td>
		<td></td>
	</tr>
</table>

</div>
<% 	} 
%>
</body>
</html>